﻿using ScottPlot.Avalonia;
using Digitalmes.Core.Services;

namespace Digitalmes.AvaloniaUI.ViewModels;

/// <summary>
/// 实时数据图表
/// </summary>
public sealed partial class TurntableRealtimePlotViewModel : ViewModelBase
{
    private readonly ITurntableRealtimeService _turntableRealtimeService;

    // 查询--开始时间
    [ObservableProperty]
    public partial DateTime? StartDate { get; set; }

    // 查询--结束时间
    [ObservableProperty]
    public partial DateTime? EndDate { get; set; }

    /// <summary>
    /// 转速
    /// </summary>
    public AvaPlot PlotRotationalSpeed { get; }

    // 查询
    [RelayCommand]
    private async Task Query()
    {
        // 查询实时数据
        var realtimeData = await _turntableRealtimeService.GetListAsync(StartDate, EndDate);

        // 转速
        double[] rotationalSpeedDataY = realtimeData.Select(m => m.RotationalSpeed).ToArray();
        BindLinePlot(PlotRotationalSpeed, rotationalSpeedDataY);
    }

    public TurntableRealtimePlotViewModel( ITurntableRealtimeService rotationalSpeedService)
    {
        _turntableRealtimeService = rotationalSpeedService;

        // 实时数据图表
        PlotRotationalSpeed = new AvaPlot();
        PlotRotationalSpeed.Plot.Title("转速");
        PlotRotationalSpeed.Plot.YLabel("转速");
        PlotRotationalSpeed.Plot.Font.Automatic();
    }

    // 绑定 Line 类型 Plot
    private static void BindLinePlot<T>(AvaPlot avaPlot, T[] dataY, double? minLimit = default, double? maxLimit = default)
        where T : struct
    {
        avaPlot.Plot.Clear();
        if (minLimit is not null)
        {
            avaPlot.Plot.Add.HorizontalLine(minLimit.Value, width: 1, color: ScottPlot.Color.FromColor(System.Drawing.Color.Red)); // 下限线
        }
        if (maxLimit is not null)
        {
            avaPlot.Plot.Add.HorizontalLine(maxLimit.Value, width: 1, color: ScottPlot.Color.FromColor(System.Drawing.Color.Red)); // 上限线
        }

        avaPlot.Plot.Add.Signal(dataY);
        avaPlot.Plot.Axes.AutoScale(); // reset limits to fit the data
        avaPlot.Refresh(); // 立即刷新图表
    }
}
